import React from 'react';
import { Form, Upload, Button } from 'dw-mx';
import { UploadOutlined } from 'dw-mx-icons';
import { request } from 'dw-mx-request';

export default function UploadDemo(props) {
    const reqTarget = props.target;

    const [form] = Form.useForm();

    const doUpload = async () => {
        const values = form.getFieldsValue();

        // 组织 FormData
        const formdata = new FormData();
        formdata.append('singlefile', values['singlefile'][0].originFileObj, values['singlefile'][0].name);
        formdata.append('xm', '张三');
        const ret = await request(`/${reqTarget}/mx/test/fileupload`, formdata);
        alert(ret);
    };

    return (
        <>
            <Form form={form}>
                <Form.Item
                    name="singlefile"
                    label="单文件"
                    valuePropName="fileList"
                    getValueFromEvent={(e) => {
                        if (Array.isArray(e)) {
                            return e;
                        }
                        return e && e.fileList;
                    }}
                >
                    <Upload beforeUpload={(file) => false}>
                        <Button>
                            <UploadOutlined /> 选择文件
                        </Button>
                    </Upload>
                </Form.Item>

                <Form.Item
                    name="multifile"
                    label="多文件"
                    valuePropName="fileList"
                    getValueFromEvent={(e) => {
                        if (Array.isArray(e)) {
                            return e;
                        }
                        return e && e.fileList;
                    }}
                >
                    <Upload beforeUpload={(file) => false} multiple={true}>
                        <Button>
                            <UploadOutlined /> 选择文件
                        </Button>
                    </Upload>
                </Form.Item>
            </Form>

            <Button onClick={doUpload}>上传</Button>
        </>
    );
}
